/*
 * @Author: kanglang
 * @Date: 2021-02-23 11:22:57
 * @LastEditors: zeki mini
 * @LastEditTime: 2021-06-10 16:05:19
 * @Description: 企业认证须知
 */

import React from 'react';
import { View, StyleSheet, Text, SafeAreaView } from 'react-native';
import { Button, Check, msg, AsyncStorage, cache } from '@/common';
import {
  px2dp,
  mainBgColorWhite,
  fontColorBlack,
  mainThemeColor,
} from '@/styles';
import { backWhite } from '@/images';
import ImageViewer from '@/components/XmImageViewer';
import CheckExampleImg from './components/check-example-img';

const { Submit } = Button;

export default class CertiKnow extends React.Component {
  constructor(props) {
    super(props);
    const { navigation } = props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { routerFrom } = params;
    this.state = {
      checked: false,
      modalVisible: false,
      imageSources: [],
      routerFrom,
      cacheList: [
        cache.BUSINESS_INFO_CERTI,
        cache.LEGAL_INFO_CERTI,
        cache.CORPORATE_ACCOUNT_INFO_CERTI,
        cache.BUSINESS_MANAGE_SET_CERTI
      ],
    };
  }

  componentDidMount() { }

  render() {
    const { checked, modalVisible, imageSources } = this.state;

    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.inner}>
          <Text style={styles.fontText}>尊敬的用户</Text>
          <Text style={styles.fontText}>您好！</Text>
          <Text style={styles.fontText}>欢迎进入小马国炬企业认证流程，本流程分为四步完成，为保障信息填写的完整性和必要性，请您在认证时提前准备以下资料：</Text>
          <Text style={styles.fontTitle}>第一步：企业信息填写 </Text>
          <Text style={styles.fontText}>
            上传最新营业执照原件的彩色照片或扫描件，如使用复印件请加盖公章，支持JPG/JPEG格式，最大10M,
            <CheckExampleImg title='查看示例1' onPress={() => this.checkTemp(1)} />
          </Text>
          <Text style={styles.fontTitle}>第二步：法人信息填写 </Text>
          <Text style={styles.fontText}>
            请分别上传法人身份证的正反面原件的彩色照片或扫描件，如使用复印件请加盖公章，支持JPG/JPEG格式，最大10M
            <CheckExampleImg title='查看示例2' onPress={() => this.checkTemp(2)} />
          </Text>
          <Text style={styles.fontTitle}>第三步：对公账户填写 </Text>
          <Text style={styles.fontText}>
            准备一张企业对公账户
            {/* （仅限广发银行对公账户卡），并已经开通线上银企直联业务，上传银企直联业务线上授权书 */}
            {/* <CheckExampleImg title='查看示例3' onPress={() => this.checkTemp(3)} /> */}
          </Text>
          <Text style={styles.fontTitle}>第四步：管理员授权 </Text>
          <Text style={styles.fontText}>
            请上传企业业务授权书
            <CheckExampleImg title='查看示例4' onPress={() => this.checkTemp(4)} />
          </Text>
          <View style={styles.btnBox}>
            <Submit
              disabled={!checked}
              text='现在去企业认证'
              btnTextStyle={{ fontSize: px2dp(32) }}
              boxStyle={styles.boxStyle}
              onClick={this.toCerti}
            />
            <View style={styles.agreementBox}>
              <Check
                checked={checked}
                onCheck={this.switchChecked}
              />
              <Text style={styles.agreementText}>
                我已阅读并同意签署
                <Text
                  style={styles.agreement}
                  onPress={this.checkAgreement}
                >
                  《企业用户注册协议》
                </Text>
              </Text>
            </View>
          </View>
          <ImageViewer
            leftBackIcon={backWhite}
            showViewModal={() => this.setState({ modalVisible: false })}
            previewModal={modalVisible}
            images={imageSources}
          />
        </View>
      </SafeAreaView>
    );
  }

  checkTemp = (type) => {
    let tempImgs = [];
    if (type === 1) {
      // 企业执照
      tempImgs = [
        {
          url:
            'https://xmgj2020-prod.oss-cn-chengdu.aliyuncs.com/businessExample/023C5048CEC147F694DRR1E1C748B1D1.jpg',
        },
      ];
    } else if (type === 2) {
      // 法人身份证
      tempImgs = [
        {
          url:
            'https://xmgj2020-prod.oss-cn-chengdu.aliyuncs.com/businessExample/023C5048CEC147F694DRR1E1C748B1D4.jpg',
        },
        {
          url:
            'https://xmgj2020-prod.oss-cn-chengdu.aliyuncs.com/businessExample/023C5048CEC147F694DRR1E1C748B1D5.jpg',
        },
      ];
    } else if (type === 3) {
      tempImgs = [
        {
          url:
            'https://xmgj2020-prod.oss-cn-chengdu.aliyuncs.com/businessExample/023C5048CEC147F694DRR1E1C748B1D6.jpg',
        },
      ];
    } else if (type === 4) {
      tempImgs = [
        {
          url:
            'https://xmgj2020-prod.oss-cn-chengdu.aliyuncs.com/businessExample/023C5048CEC147F694DRR1E1C748B1D2.jpg',
        },
        {
          url:
            'https://xmgj2020-prod.oss-cn-chengdu.aliyuncs.com/businessExample/023C5048CEC147F694DRR1E1C748B1D3.jpg',
        },
      ];
    }
    this.setState({
      modalVisible: true,
      imageSources: tempImgs,
    });
  };

  checkAgreement = () => {
    msg.emit('router: goToNext', {
      routeName: 'CustAgreement',
      routerFrom: 'businessRegisterAgreement',
    });
  };

  switchChecked = () => {
    const { checked } = this.state;
    this.setState({ checked: !checked });
  };

  toCerti = () => {
    const { checked } = this.state;
    if (!checked) return msg.emit('app: tip', { text: '请先阅读协议' });

    this.checkIsCache(0);
  };

  // 判断是否已经认证过
  checkIsCache = (index) => {
    const { routerFrom, cacheList } = this.state;
    if (index > cacheList.length - 1) {
      console.log(routerFrom);
      msg.emit('router: goToNext', {
        routeName: 'BusinessInfoCerti',
        routerFrom
      });
    } else {
      const key = cacheList[index];
      AsyncStorage.getItem(key).then((data) => {
        const dataCache = JSON.parse(data) || {};
        const cacheData = dataCache[cacheList[index]];
        if (cacheData && cacheData !== '') {
          this.showAnnotationAlert();
        } else {
          index += 1;
          this.checkIsCache(index);
        }
      }).catch(err => {
        console.log('信息异常：', index, err);
        index += 1;
        this.checkIsCache(index);
      });
    }
  };

  // 弹窗提示是否继续
  showAnnotationAlert = () => {
    const { routerFrom } = this.state;
    msg.emit('app:messageBox', {
      isVisible: true,
      text: '认证信息暂未完成，是否继续？',
      okText: '确定',
      cancelText: '取消',
      okFn: () => {
        msg.emit('router: goToNext', {
          routeName: 'BusinessInfoCerti',
          routerFrom
        });
      },
      cancelFn: () => {
        const { cacheList } = this.state;
        cacheList.forEach(key => {
          AsyncStorage.setItem(key, '');
        });
        msg.emit('router: goToNext', {
          routeName: 'BusinessInfoCerti',
          routerFrom
        });
      },
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorWhite,
  },
  inner: {
    flex: 1,
    backgroundColor: mainBgColorWhite,
    paddingHorizontal: px2dp(32),
    paddingVertical: px2dp(41),
  },
  fontTitle: {
    color: fontColorBlack,
    fontSize: px2dp(32),
    marginTop: px2dp(32),
    lineHeight: px2dp(40),
  },
  fontText: {
    color: fontColorBlack,
    fontSize: px2dp(28),
    lineHeight: px2dp(38),
  },
  tempText: {
    color: '#2293FF',
    fontSize: px2dp(28),
    textDecorationLine: 'underline',
  },
  btnBox: {
    flex: 1,
    alignItems: 'center',
    marginTop: px2dp(130),
  },
  boxStyle: {
    width: px2dp(640),
    height: px2dp(96),
    borderRadius: px2dp(12),
    overflow: 'hidden',
  },
  agreementBox: {
    flexDirection: 'row',
    marginTop: px2dp(32),
  },
  agreementText: {
    marginLeft: px2dp(16),
  },
  agreement: {
    paddingLeft: px2dp(16),
    color: mainThemeColor,
  },
});
